package com.aabte.auth.account.resource.facade;

import com.aabte.auth.account.domain.model.AccountId;
import com.aabte.auth.account.resource.api.group.GroupDTO;
import com.aabte.auth.account.resource.facade.assembler.GroupDTOAssembler;
import com.aabte.auth.group.application.GroupService;
import com.aabte.auth.group.domain.model.Group;
import com.aabte.auth.group.domain.model.GroupId;
import com.aabte.auth.group.domain.model.GroupName;
import com.aabte.auth.role.domain.model.RoleId;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component
public class GroupServiceFacade {
    @Resource
    private GroupService groupService;

    public String create(String groupName) {
        return groupService.create(new GroupName(groupName)).getId();
    }

    public boolean delete(String groupId) {
        return groupService.delete(new GroupId(groupId));
    }

    public void addAccount(String groupId, String accountId) {
        groupService.addAccount(new GroupId(groupId), new AccountId(accountId));
    }

    public void addRole(String groupId, String roleId) {
        groupService.addRole(new GroupId(groupId), new RoleId(roleId));
    }

    public Page<GroupDTO> groups(Integer pageNumber, Integer pageSize) {
        Pageable pageable = PageRequest.of(pageNumber - 1, pageSize);
        Page<Group> groupPage = groupService.groups(pageable);
        return toDTO(groupPage);
    }

    private Page<GroupDTO> toDTO(Page<Group> groupPage) {
        GroupDTOAssembler assembler = new GroupDTOAssembler();

        List<GroupDTO> content = new ArrayList<>(groupPage.getNumberOfElements());
        for (Group group : groupPage.getContent()) {
            content.add(assembler.toDTO(group));
        }

        return new PageImpl<>(
                content, groupPage.getPageable(), groupPage.getTotalElements());
    }
}
